﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Xiaov.SmartWeb.Model.ActiveRecord;
using Xiaov.SmartWeb.Infrastructure.ExtMethod;
using Xiaov.SmartWeb.Infrastructure.Common;
using System.Data;

namespace Xiaov.SmartWeb.Application.PluginSrc.StatisticalSystem.ReportDesign.Json
{
  public partial class BBBMB : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      //单位编码
      string dwbm = Request["dwbm"].ToRequestString();

      if (dwbm != "")
      {
        DataTable dt = Maticsoft.DBUtility.DbHelperOra.Query(@"select p.bbbm,q.bbwh||'['||v.lbmc||']'||q.bbmc as bbmc,p.cb,p.parentid from (

select x.bbbm,y.bbbm as cb,'0' as parentid from code_bbbmb x,(select a.bbmc as bbmc,a.bbbm,a.bblx from bbdytbdw t right join code_bbbmb a on t.bbbm=a.bbbm where t.dwbm='" + dwbm + "')y where x.bbbm=y.bbbm(+) order by  x.bbbm asc) p ,code_bbbmb q,enco_bblx v where p.bbbm=q.bbbm and q.bblx=v.id order by q.bblx,q.pxxh ").Tables[0];
        Response.Clear();
        Response.Write(ToJsonForTree_Sepcial(dt, "BBBM", "BBMC", "Parentid", "0"));

        Response.End();
      }
      else
      {
        DataTable dt = Maticsoft.DBUtility.DbHelperOra.Query("select BBBM,''||BBWH||'['||lbmc||']'||BBMC as bbmc from code_bbbmb t,enco_bblx y where t.bblx=y.id order by t.bblx,t.pxxh").Tables[0];
        Response.Clear();
        Response.Write(dt.ToJsonForCombobox("BBBM", "BBMC", ""));
        Response.End();
      }


    }

    private string ToJsonForTree_Sepcial(DataTable dt, string idField, string textField, string parentIdField, string rootIdValue)
    {
      string JsonData = "[";
      DataRow[] drs = dt.Select(parentIdField + "='" + rootIdValue + "'");
      foreach (var d in drs)
      {
        JsonData += "{";

        JsonData += "\"text\":\"" + d[textField].ToString() + "\",";
        JsonData += "\"id\":\"" + d[idField].ToString() + "\",";
        if (d["CB"].ToRequestString() != "")
          JsonData += "\"checked\":true,";
        DataRow[] childdrs = dt.Select(parentIdField + "='" + d[idField] + "'");
        if (childdrs.Count() > 0)
        {
          JsonData += "\"children\":";
          JsonData += ToJsonForTree_Sepcial(dt, idField, textField, parentIdField, d[idField].ToString());
          JsonData += "},";
        }
        else
        {
          JsonData = JsonData.Remove(JsonData.Length - 1);
          JsonData += "},";
        }
      }
      if (JsonData.Length > 1)
        JsonData = JsonData.Remove(JsonData.Length - 1);
      JsonData += "]";
      return JsonData;
    }
  }
}